package com.longshihan.module_toutiao.mvp.ui.fragment;


import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.longshihan.module_toutiao.R;
import com.longshihan.mvplh.widget.SuperFileView2;
import com.tencent.smtt.sdk.TbsReaderView;

import java.io.File;


/**
 * A simple {@link Fragment} subclass.
 * miui 兼容性不好
 */
public class AndroidFragment extends Fragment implements View.OnClickListener, TbsReaderView.ReaderCallback {
    TextView mFragmentBtn;
    View view;
    private String filePath = "";
    private File file;
    private String fileName = "";
    private SuperFileView2 mSuperFileView;

    public AndroidFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_android, container, false);
        initView(view);
        return view;
    }

    private void initView(View view) {
        this.mFragmentBtn = (TextView) view.findViewById(R.id.fragment_btn);
        mSuperFileView = (SuperFileView2) view.findViewById(R.id.fragment_frame);
        mFragmentBtn.setOnClickListener(this);

        mSuperFileView.setOnGetFilePathListener(new SuperFileView2.OnGetFilePathListener() {
            @Override
            public void onGetFilePath(SuperFileView2 mSuperFileView2) {
               // getFilePathAndShowFile(mSuperFileView2);
                mSuperFileView2.displayFile(new File("/storage/emulated/0/Download/24586.txt"));
            }
        });

        Intent intent = getActivity().getIntent();
        String path = (String) intent.getSerializableExtra("path");

        if (!TextUtils.isEmpty(path)) {
           // setFilePath(path);
        }
        mSuperFileView.show();

    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("application/msword");   //打开文件类型   Word文档
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, 1);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {
            return;
        }
        Uri uri = data.getData();//得到uri，后面就是将uri转化成file的过程。

        if (!uri.getPath().equals(filePath)) {//判断是否第二次选择文件
            file = null;
        }

        //获取到选中文件的路径
        filePath = uri.getPath();

        //判断是否是外部打开
        if (filePath.contains("external")) {
            isExternal(uri);
        }
        //获取的是否是真实路径
        if (file == null) {
            isWhetherTruePath(uri);
        }
        //如果前面都获取不到文件，则自己拼接路径
        if (file == null) {
            splicingPath(uri);
        }
        Log.i("hxl", "路径转化成的file=========" + file);
        Bundle bundle = new Bundle();

        bundle.putString("filePath", file.toString());
        bundle.putString("tempPath", Environment.getExternalStorageDirectory().getPath()+"/007");
        mSuperFileView.displayFile(new File("/storage/emulated/0/007/47ab273ab2d89e34db3b890e2c1d2523.doc"));

    }

    private String parseFormat(String fileName) {
        return fileName.substring(fileName.lastIndexOf(".") + 1);
    }

    /**
     * 拿到文件外部路径，通过外部路径遍历出真实路径
     *
     * @param uri
     */
    private void isExternal(Uri uri) {
        Log.i("hxl", "获取文件的路径filePath=========" + filePath);
        Log.i("hxl", "===调用外部遍历出路径方法===");
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor actualimagecursor = getActivity().managedQuery(uri, proj, null, null, null);
        int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        actualimagecursor.moveToFirst();
        String img_path = actualimagecursor.getString(actual_image_column_index);
        file = new File(img_path);
//        Log.i("hxl", "file========="+file);
        filePath = file.getAbsolutePath();
        if (!filePath.endsWith(".doc")) {
            Toast.makeText(getContext(), "您选中的文件不是Word文档", Toast.LENGTH_LONG).show();
            filePath = null;
            return;
        }

    }


    /**
     * 判断打开文件的是那种类型
     *
     * @param uri
     */
    private void isWhetherTruePath(Uri uri) {
        try {
            Log.i("hxl", "获取文件的路径filePath=========" + filePath);
            if (filePath != null) {
                if (filePath.endsWith(".doc")) {
                    if ("file".equalsIgnoreCase(uri.getScheme())) {//使用第三方应用打开
                        filePath = getPath(getContext(), uri);
                        Log.i("hxl", "===调用第三方应用打开===");
                        fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
                        file = new File(filePath);
                    }
                    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {//4.4以后
                        Log.i("hxl", "===调用4.4以后系统方法===");
                        filePath = getRealPathFromURI(uri);
                        fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
                        file = new File(filePath);
                    } else {//4.4以下系统调用方法
                        filePath = getRealPathFromURI(uri);
                        Log.i("hxl", "===调用4.4以下系统方法===");
                        fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
                        file = new File(filePath);
                    }
                } else {
                    Toast.makeText(getContext(), "您选中的文件格式不是Word文档", Toast.LENGTH_LONG).show();
                }
//                Log.i("hxl", "file========="+file);
            } else {

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 专为Android4.4设计的从Uri获取文件绝对路径，以前的方法已不好使
     */
    @TargetApi(Build.VERSION_CODES.KITKAT)
    public String getPath(final Context context, final Uri uri) {

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }

            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{split[1]};

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }
        return null;
    }


    public String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {column};

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }


    //获取文件的真实路径
    public String getRealPathFromURI(Uri contentUri) {
        String res = null;
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = getActivity().getContentResolver().query(contentUri, proj, null, null, null);
        if (cursor.moveToFirst()) {
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            res = cursor.getString(column_index);
        }
        cursor.close();
        return res;
    }

    /**
     * 如果前面两种都获取不到文件
     * 则使用此种方法拼接路径
     * 此方法在Andorid7.0系统中可用
     */
    private void splicingPath(Uri uri) {
        Log.i("hxl", "获取文件的路径filePath=========" + filePath);
        if (filePath.endsWith(".doc")) {
            Log.i("hxl", "===调用拼接路径方法===");
            String string = uri.toString();
            String a[] = new String[2];
            //判断文件是否在sd卡中
            if (string.indexOf(String.valueOf(Environment.getExternalStorageDirectory())) != -1) {
                //对Uri进行切割
                a = string.split(String.valueOf(Environment.getExternalStorageDirectory()));
                //获取到file
                file = new File(Environment.getExternalStorageDirectory(), a[1]);
            } else if (string.indexOf(String.valueOf(Environment.getDataDirectory())) != -1) { //判断文件是否在手机内存中
                //对Uri进行切割
                a = string.split(String.valueOf(Environment.getDataDirectory()));
                //获取到file
                file = new File(Environment.getDataDirectory(), a[1]);
            }
//            fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
//            Log.i("hxl", "file========="+file);
        } else {
            Toast.makeText(getContext(), "您选中的文件不是Word文档", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onCallBackAction(Integer integer, Object o, Object o1) {

    }

    /***
     * 获取文件类型
     *
     * @param paramString
     * @return
     */
    private String getFileType(String paramString) {
        String str = "";

        if (TextUtils.isEmpty(paramString)) {
            return str;
        }
        int i = paramString.lastIndexOf('.');
        if (i <= -1) {
            return str;
        }


        str = paramString.substring(i + 1);
        return str;
    }
}
